package com.leetcode;

import com.leetcode.common.TreeNode;

import java.util.*;

/**
 * 107. 二叉树的层序遍历 II
 *
 * @author fy
 * @date 2022/4/14 20:10
 */
public class Solution107 {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Deque<List<Integer>> stack = new LinkedList<>();

        queue.offer(root);
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            List<Integer> levels = new ArrayList<>();
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                levels.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            stack.push(levels);
        }
        while (!stack.isEmpty()) {
            res.add(stack.pop());
        }
        return res;
    }

}
